<template>
  <div ref="container" :style="{ height: props.height ? props.height + 'px' : '300px' }"></div>
</template>

<script setup lang="ts">
  import { ref, onMounted, watch, onUnmounted } from 'vue'
  import * as echarts from 'echarts'
  const container = ref<HTMLElement | null>(null)
  const props = defineProps({
    option: Object,
    height: Number,
  })
  let myEcharts
  watch(
    () => props.option,
    () => {
      if (props.option) {
        myEcharts = echarts.init(container.value)
        props.option && myEcharts.setOption(props.option)
      }
    },
    { deep: true },
  )

  onMounted(() => {
    if (props.option) {
      myEcharts = echarts.init(container.value)
      props.option && myEcharts.setOption(props.option)
    }
    window.addEventListener('resize', chartsResize)
  })

  onUnmounted(() => {
    myEcharts?.dispose()
    myEcharts = null
    window.removeEventListener('resize', chartsResize)
  })

  function chartsResize() {
    if (!myEcharts) return
    myEcharts.resize()
  }
</script>
